import { login, getUserInfo, getUserDetailById } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 将token存到vuex里
    SET_TOKEN(state, token) {
      state.token = token
      // 把token存到cookie里
      setToken(token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 清除token
    REMOVE_TOKEN(state) {
      state.token = ''
      removeToken()
    }
  },
  actions: {
    // 声明个方法 第二个参数 是接口里要传的参数
    async fetchLogin(store, loginForm) {
      // 解构回调函数里的data
      const { data } = await login(loginForm)
      // .commit转化为同步放到mutations里
      store.commit('SET_TOKEN', data)
      return data
    },
    async fetchUserInfo(store) {
      const res = await getUserInfo()
      const res1 = await getUserDetailById(res.data.userId)
      store.commit('setUserInfo', { ...res.data, ...res1.data })
    }
  }
}
